﻿using System.ServiceModel.Security;
using System;
using System.Text;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;
using System.Net;
using System.IO;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ServiceModel;
using System.Activities;
using System.Threading;
using System.ServiceModel.Description;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Configuration.Assemblies;
//using MyTestWF;
//using WebServicesTesting.Automation;
using MyTestWF;
using WebServicesTesting.Automation;
using Unit_Test_Sample.DataStructure;
using System.ServiceModel.Configuration;
using System.Windows.Forms;



namespace Unit_Test_Sample
{
    [TestClass]
    public class SampleUnitTestCases
    {
        private TestContext TestContextInstance;
        public string connection_string;
        public string auth_username;
        public string auth_passwd;
        public string m_MyOperationId;
        public string var_Async_root;
        public Async_Call.MyServiceClient m_Client;


        public TestContext TestContext
        {
            get
            {
                return TestContextInstance;
            }
            set
            {
                TestContextInstance = value;
            }
        }

        [TestInitialize]
        public void initialize()
        {
            
            connection_string = System.Configuration.ConfigurationManager.AppSettings["connection_string"];
            
            auth_username = System.Configuration.ConfigurationManager.AppSettings["auth_username"];
            auth_passwd = System.Configuration.ConfigurationManager.AppSettings["auth_passwd"];
            //m_Client = new Async_Call.MyServiceClient();
            //m_Client.GetSquareRootCompleted += new EventHandler<Async_Call.GetSquareRootCompletedEventArgs>(client_GetSquareRootCompleted); 
                       

        }

        [TestCleanup]
        public void Cleanup()
        {

            
        }


        [TestMethod]
        [Description("Unit test for checking the authentication of the Service"), Owner("Vipul Mehta"), 
        TestCategory("Authentication")]
        public void VerifyAuthentication()
        {
            string time = "";
            var ServiceendPoint = new EndpointAddress(new Uri("http://localhost:91/Service1.svc"), EndpointIdentity.CreateDnsIdentity("MyWebSite"));
            var binding = new WSHttpBinding();
            binding.Security.Mode = SecurityMode.Message;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;


            var result = new Auth_Service.Service1Client(binding, ServiceendPoint);
            try
            {
                result.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
                result.ClientCredentials.UserName.UserName = auth_username;
                result.ClientCredentials.UserName.Password = auth_passwd;
                time = result.GetServertime();
            }
            catch (Exception ex)
            {
                TestContext.WriteLine("Error- " + ex.Message);
            }

            if (time.Length > 0)
            {
                TestContext.WriteLine("Server time returned by service is correct " + time);
            }
            else
            {
                TestContext.WriteLine("server time returned by service is incorrect which is " + time);
            }
        }

        [TestMethod]
        [Description("Unit test for checking the invoking of method using the proxy generated"), Owner("Vipul Mehta"),
        TestCategory("Proxy calls")]
        public void Proxy_call()
        {
            Service1Client proxy_obj = new Service1Client();
            int ?return_val=null;
            try
            {
                return_val = proxy_obj.GetData(5);
            }
            catch (Exception ex)
            {
                TestContext.WriteLine("Error- " + ex.Message);
            }

            if (return_val == null)
            {
                TestContext.WriteLine("Null was returnes , there was some problem with the execution of proxy method. ");
            }
            else
            {
                TestContext.WriteLine("Computational value after proxy call is " + return_val);
            }

            
        }



        [TestMethod]
        [Description("Unit test for checking the Asynchronous call to the service"), Owner("Vipul Mehta"),
        TestCategory("Asynchronous calls")]
        public void VerifyAsync_Response()
        {
            //Uri httpUrl = new Uri("http://localhost:8080/MyService/");
            //ServiceHost host = new ServiceHost(typeof(TestAsync.MyService), httpUrl);
            //host.AddServiceEndpoint(typeof(TestAsync.IMyService), new BasicHttpBinding(), "");
            //ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            //smb.HttpGetEnabled = true;
            //host.Description.Behaviors.Add(smb);
            //host.Open();                
            ServiceHost host = new ServiceHost(typeof(TestAsync.MyService));
            host.Open();

            var_Async_root = "4";
            double value = 0;
            Double.TryParse(var_Async_root, out value);

            m_MyOperationId = Guid.NewGuid().ToString();

            m_Client.GetSquareRootAsync(value, m_MyOperationId);

            //string p = "asdsda";
        }

        void client_GetSquareRootCompleted(object sender, Async_Call.GetSquareRootCompletedEventArgs e)
        {
            if ((string)e.UserState == m_MyOperationId)
            {
                string return_value = e.Result.ToString();
            }
        }


        [TestMethod]
        [Description("Unit test for verifying the of execution of WCF using the self host"), Owner("Vipul Mehta"),
        TestCategory("SelfHosting")]
        public void Verify_Selfhost_Test()
        {
            ServiceHost svcHost = new ServiceHost(typeof(Console_Test.Service_Console), new Uri("http://localhost:8001/MetadataSample"));
            try
            {
                ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                    smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                svcHost.Description.Behaviors.Add(smb);
                svcHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
                svcHost.AddServiceEndpoint(typeof(Console_Test.IService_Console), new WSHttpBinding(), "");
                svcHost.Open();
                Self_Host.Service1Client Self_Host_Obj = new Self_Host.Service1Client();
                int X = 5, y = 7;
                int result = Self_Host_Obj.add(X, y);
                TestContext.WriteLine("Result obtained after the method execution is " + result);
                svcHost.Close();
            }
            catch (CommunicationException commProblem)
            {
                Console.WriteLine("There was a communication problem. " + commProblem.Message);
                Console.Read();
            }

        }


        [TestMethod]
        [Description("Unit test for verifying the service call for message level encryption"), Owner("Vipul Mehta"),
        TestCategory("Encryption")]
        public void VerifyEncryption()
        {
            string binding_used;
            binding_used = "";
            Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);
            Console.WriteLine("Configuration Name : Address : Binding : Contract");
            foreach (ChannelEndpointElement endpoint in serviceModel.Client.Endpoints)
            {
                if (endpoint.Contract == "Auth_Service.IService1")
                {
                    binding_used = endpoint.Binding;
                    break;
                }
                else
                {
                }
            }

            Auth_Service.Service1Client result = new Auth_Service.Service1Client();
            result.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            result.ClientCredentials.UserName.UserName = auth_username;
            result.ClientCredentials.UserName.Password = auth_passwd;
            string time = result.GetServertime();
            TestContext.WriteLine("Bindings used by this contract is " + binding_used);


        }

        [TestMethod]
        [Description("Unit test for verifying non-xml data like image etc returned as stream from web service call"), Owner("Vipul Mehta"), 
        TestCategory("Non XML Data")]
        public void VerifyNonXMLData()
        {
            Uri httpUrl = new Uri("http://localhost:8500/WCFSamples/Streaming/");
            ServiceHost host = new ServiceHost(typeof(Buffered_Response.ServiceImpl), httpUrl);
            host.AddServiceEndpoint(typeof(Buffered_Response.IStreamingService), new BasicHttpBinding("WCFSamples_Buffered"), "");
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            host.Open();
           // Buffered_Response.ServiceImpl ClientHandle = new Buffered_Response.ServiceImpl();
            ImageServc.StreamingServiceClient ClientHandle = new ImageServc.StreamingServiceClient();
            ResponseXmlInterceptingBehavior responseXmlInterceptingBehaviour = new ResponseXmlInterceptingBehavior();
            ClientHandle.Endpoint.Behaviors.Add(responseXmlInterceptingBehaviour);
            Stream OutputFile = null;

            try
            {
                OutputFile = ClientHandle.GetData("Dryden");

                if (OutputFile != null)
                {
                    System.Drawing.Bitmap RawImage = new Bitmap(OutputFile);
                    OutputFile.Close();
                    TestContext.WriteLine("Service returned the data as expected. ");
                }
                else
                {
                    TestContext.WriteLine("Service did not returned the data as expected" );
                }
            }
            catch (FaultException<IOException> ioExcept)
            {
                
            }
            catch (CommunicationException comExcept)
            {
                
            }
            

            host.Close();
        }

        [Description("Sample Unit TestCase to Verify that web service inserted records to a database"),
        Owner("Ranjit Gupta"),
        TestCategory("Transactional Verification")]
        [TestMethod]
        public void VerifyDatabaseInsertScenario()
        {
           
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
                string fname = "asd";
                string lname = "asddfd";
                int age = 904;
                int mo = 34;
                obj.Enroll_Student(fname, lname, age, mo);

                string query = "select First_Name,Last_Name,Age,Marks_Obtained from Sample_App where Age=904";
                string conn = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
                string expected = fname + "," + lname + "," + age.ToString() + "," + mo.ToString();
                UnitTest help = new UnitTest();
                
                #if WEBSERVICES_FUNCTIONAL_TESTING
                      help.Verify_DbInsert(conn, query, expected);
                #endif
                #if WEBSERVICES_LOAD_TESTING
                                //Any specific code if you want to run for Load testing alone
                #endif


        }
        
        [Description("Sample Unit TestCase to Verify that web service updated records from a database"),
        Owner("Ranjit Gupta"),
        TestCategory("Transactional Verification")]
        [TestMethod]
        public void VerifyDatabaseUpdateScenario()
        {
            
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();


                string f_name = "abcd";
                string l_name = "abcd";
                int age = 55;
                int mo = 33;
                int roll = 11;
                string query = "select First_Name,Last_Name,Age,Marks_Obtained,Roll_Number from Sample_App where Roll_Number=11";
                string conn = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";

                obj.Update_Student(f_name, l_name, age, mo, roll);
                string expected = f_name + ", " + l_name + ", " + age + ", " + mo + ", " + roll;
                UnitTest help = new UnitTest();
                

                #if WEBSERVICES_FUNCTIONAL_TESTING
                    help.Verify_DBUpdate(conn, query, expected);
                #endif
                #if WEBSERVICES_LOAD_TESTING
                    //Any specific code if you want to run for Load testing alone
                #endif


        }
       
        [Description("Sample Unit TestCase to Verify that web service deleted records from a database"),
        Owner("Ranjit Gupta"),
        TestCategory("Transactional Verification")]
        [TestMethod]
        public void VerifyDatabaseDeleteScenario()
        {
            
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
                int roll=20;
                string query = "select First_Name,Last_Name,Age,Marks_Obtained,Roll_Number from Sample_App where Roll_Number=20";
                string conn = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
                obj.Delete_Student(roll);
                UnitTest help = new UnitTest();
                

                #if WEBSERVICES_FUNCTIONAL_TESTING
                     help.Verify_DBDelete(conn, query);
                #endif
                #if WEBSERVICES_LOAD_TESTING
                    //Any specific code if you want to run for Load testing alone
                #endif
         }
        
        [Description("Sample Unit TestCase to Verify result set returned against expected result set /table"),
        Owner("Ranjit Gupta"),
        TestCategory("Transactional Verification")]
        [TestMethod]
        public void VerifyDataset()
        {
                string[,] table = new string[100, 100];
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
                DataSet set = new DataSet();
                string query = "select * from Sample_App where First_Name='Raj'";
                string conn = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
                set = obj.Display();

                UnitTest help = new UnitTest();


                #if WEBSERVICES_FUNCTIONAL_TESTING
                     help.Verify_Dataset(conn, query, set);
                #endif
                #if WEBSERVICES_LOAD_TESTING
                     //Any specific code if you want to run for Load testing alone
                #endif
                
                     
        }
       
    
        [Description("Sample Unit TestCase to Verify web service created the file (CSV/XML) as expected"),
        Owner("Ranjit Gupta"),
        TestCategory("File Creation")]
        [TestMethod]
        public void VerifyFileCreation()
        {
            WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
            obj.Create_File();
           
       
            #if WEBSERVICES_FUNCTIONAL_TESTING
                UnitTest help = new UnitTest();
                help.Verify_FileCreation("D:\\employees.xml");
            #endif
            #if WEBSERVICES_LOAD_TESTING
                   //Any specific code if you want to run for Load testing alone
            #endif
                
        }

        [Description("Sample Unit TestCase to Verify schema definition"),
        Owner("Ranjit Gupta"),
        TestCategory("Schema Verification")]
        [TestMethod]
        public void VerifyWebServiceSchema()
        {
            string fname = "asdqwe";
            string lname = "asddfdfgg";
            int age = 541;
            int mo = 34;
            
            WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
            ResponseXmlInterceptingBehavior responseXmlInterceptingBehaviour = new ResponseXmlInterceptingBehavior();
            obj.Endpoint.Behaviors.Add(responseXmlInterceptingBehaviour);
            obj.Enroll_Student(fname, lname, age, mo);
            string requestXml = responseXmlInterceptingBehaviour.ResponseXmlInterceptor.RequestXml;
            UnitTest help = new UnitTest();
            bool validation = help.Verify_Schema("http://tempuri.org/", "D:\\WebService\\WcfService2\\WcfService\\Service References\\ServiceReference1\\Service11.xsd", requestXml);
            Assert.AreEqual(validation, true, "Xchema does not match");
        }

        [DeploymentItem("Method.csv"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Method.csv", "Method#csv", DataAccessMethod.Sequential), Description("Sample Unit TestCase to Verify the method prototype"),
        Owner("Ranjit Gupta"),
        TestCategory("Schema Verification")]
        [TestMethod]
        public void VerifyWebServiceMethodSignature()
        {

            WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
            UnitTest help = new UnitTest();
            string methodlist = TestContextInstance.DataRow["MethodName"].ToString();
            string paramlist = TestContextInstance.DataRow["ParamList"].ToString();
            string returnTypelist = TestContextInstance.DataRow["ReturnType"].ToString();
            // bool validation = help.methodExistenceVerification(obj, methodlist);
            help.Verify_methodPrototype(obj, methodlist, paramlist, returnTypelist);
            
        }

        [Description("Sample Unit TestCase to Verify that service returns appropriate error message"),
        Owner("Ranjit Gupta"),
        TestCategory("Exceptions and Error Handling")]
        [TestMethod]
        public void VerifyWebServicesExceptions()
        {
            try
            {
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
                obj.Display();
            }

            catch (FaultException e)
            {
                string str = e.Message.ToString();
                TestContext.WriteLine(str);
            }
        }
    
        [Description("Sample Unit TestCase to Verify the results from different web services calls by merging them"),
        Owner("Ranjit Gupta"),
        TestCategory("Merging")]
        [TestMethod]
        public void VerifyMergeWebServicesResults()
        {
            
                WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
                string expected = "5 Test";
                string exmaple1 = obj.mergeExample().ToString();
                string example2 = obj.mergeExample1();
                string actual = exmaple1 + " "+ example2;
                Assert.AreEqual(expected, actual);
        }
       
        [Description("Sample Data-driven Unit TestCase where Webservice output is a single scaler value"),
        Owner("Gunjan Jain"),
        TestCategory("Lookup Verification")]
        [DataSource("System.Data.SqlClient", "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True", "Sample_App", DataAccessMethod.Sequential), TestMethod]

        public void VerifyScalarResponseValue()
        {
            string age = TestContextInstance.DataRow["Age"].ToString();
            UnitTest obj = new UnitTest();
            string getAgeActual;
            string getAgeExpected;
            ASMXServiceRef.Service1SoapClient Ser1 = new ASMXServiceRef.Service1SoapClient();
            getAgeActual = (Ser1.GetAdultorNot(age) ?? string.Empty).ToString();
            getAgeExpected = (TestContextInstance.DataRow["AdultorNot"] ?? string.Empty).ToString();


            #if WEBSERVICES_FUNCTIONAL_TESTING
                obj.CompareString(1, getAgeExpected, getAgeActual);
            #endif
            #if WEBSERVICES_LOAD_TESTING
                         //Any specific code if you want to run for Load testing alone
            #endif
            

            
                      
        }

        [Description("Sample Unit TestCase where Webservice output is a single scaler value"),
         Owner("Gunjan Jain"),
         TestCategory("Lookup Verification")]
        [TestMethod]
        public void VerifyScalarResponseValueExample2()
        {
            string age = "98";
            UnitTest obj = new UnitTest();
            ASMXServiceRef.Service1SoapClient Ser1 = new ASMXServiceRef.Service1SoapClient();

            //string query = "Select AdultorNot from Sample_App where Age = " + age;
            string query = "Select AdultorNot from Sample_App where Age ='98'";
            DataSet getAgeExpected = obj.ConvertQueryToDataset(connection_string,query);           //TestContextInstance.DataRow["AdultorNot"].ToString();
            //var getAgeActual = Ser1.GetAdultorNot(age);        

            string getAgeActual = Ser1.GetAdultorNot(age).ToString();

            #if WEBSERVICES_FUNCTIONAL_TESTING
                     string[] ArrgetAgeExpected = obj.ConvertDataSetToString(1, getAgeExpected);
                     obj.CompareString(1, ArrgetAgeExpected, getAgeActual);

            #endif
            #if WEBSERVICES_LOAD_TESTING
                     //Any specific code if you want to run for Load testing alone
            #endif
                       


        }
        
        [Description("Sample Unit TestCase where Webservice output is N scalar values"),
        Owner("Gunjan Jain"),
        TestCategory("Lookup Verification")]
        [TestMethod]
        public void VerifyNScalarResponseValues()
        {
            int RollNum = 1;
            UnitTest obj = new UnitTest();
            ASMXServiceRef.Service1SoapClient Ser1 = new ASMXServiceRef.Service1SoapClient();

            string query = "Select * from Sample_App where Roll_Number = " + RollNum;

            DataSet getAgeExpected = obj.ConvertQueryToDataset(connection_string, query);           //TestContextInstance.DataRow["AdultorNot"].ToString();
            

            string getAgeActual = Ser1.GetData(RollNum).ToString();
            string[] seperator = { "," };
            string[] ArrgetAgeActual = getAgeActual.Split(seperator, System.StringSplitOptions.RemoveEmptyEntries);
                        

            #if WEBSERVICES_FUNCTIONAL_TESTING
                        string[] ArrgetAgeExpected = obj.ConvertDataSetToString(1, getAgeExpected);
                        obj.CompareString(2, ArrgetAgeExpected, ArrgetAgeActual);

            #endif
            #if WEBSERVICES_LOAD_TESTING
                                 //Any specific code if you want to run for Load testing alone
            #endif


        }

        [Description("Sample Unit TestCase where Webservice output is Dictionary"),
        Owner("Gunjan Jain"),
        TestCategory("Lookup Verification")]
        [TestMethod]
        public void VerifyDictionaryResponseValues()
        {


            WCFServiceRef.Service1Client Ser1 = new WCFServiceRef.Service1Client();

            string query = "Select Roll_Number , First_Name from Sample_App";
            UnitTest obj = new UnitTest();
                      
            DataSet getAgeExpected = obj.ConvertQueryToDataset(connection_string, query);
            string[,] ArrgetAgeExpected = obj.ConvertDataSetToStringForCol(getAgeExpected);


            Dictionary<int, string> col_Symbols = new Dictionary<int, string>();
            col_Symbols = null;
            col_Symbols = Ser1.GetRollNumbers1();

            #if WEBSERVICES_FUNCTIONAL_TESTING
                obj.CompareDictionaryWithExpectedArray(col_Symbols, ArrgetAgeExpected);

            #endif
            #if WEBSERVICES_LOAD_TESTING
                                             //Any specific code if you want to run for Load testing alone
            #endif
                                 

        }

        [Description("Sample Unit TestCase where Webservice output is List"),
        Owner("Gunjan Jain"),
        TestCategory("Lookup Verification")]
        [TestMethod]
        public void VerifyListResponseValues()
        {

            UnitTest obj = new UnitTest();
            WCFServiceRef.Service1Client Ser1 = new WCFServiceRef.Service1Client();

            string query = "Select First_Name from Sample_App";
            DataSet getExpected = obj.ConvertQueryToDataset(connection_string, query);

            string[] ArrgetAgeExpected = obj.ConvertDataSetToString(3, getExpected);
                        
            string[] col_Symbols = Ser1.GetFirstNameList();

            

            #if WEBSERVICES_FUNCTIONAL_TESTING
                obj.CompareString(0, col_Symbols, ArrgetAgeExpected);

            #endif
            #if WEBSERVICES_LOAD_TESTING
                                                         //Any specific code if you want to run for Load testing alone
            #endif

    }
       
        [Description("Sample Unit TestCase to test a workflow"),
        Owner("Ranjit Gupta"),
        TestCategory("Workflow")]
        [TestMethod]
        public void VerifyWorkflow()
        {
           
                int expected = 14;
                int arg = 5;
                IDictionary<string, object> _d = new Dictionary<string, object>() { { "userArgument", arg } };
                _d = WorkflowInvoker.Invoke(new Workflow1(), _d);
                Int32 outPut = (Int32)_d["OutputValue"];
                Assert.AreEqual(expected, outPut);
            
        }

        [Description("Sample Unit TestCase where Webservice cache functionality is verified"),
        Owner("Ranjit Gupta"),
        TestCategory("Caching")]
        [TestMethod]
        public void VerifyCaching()
        {
            string url = "http://localhost/Cache/Service1.svc/xml/12";
            Uri uri = new Uri(url);
            WebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string firstResponse = readStream.ReadLine();
                        
            request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            response = (HttpWebResponse)request.GetResponse();
            receiveStream = response.GetResponseStream();
            readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string secondResponse = readStream.ReadLine();
            if (firstResponse.Equals(secondResponse))
            {
                TestContext.WriteLine("Data retrievd from cache");
            }
            else
            {
                TestContext.WriteLine("Data not retrived from cache");
                Assert.Fail();
            }
        }

        [Description("Sample Unit TestCase where Webservice cache functionality is verified"),
        Owner("Ranjit Gupta"),
        TestCategory("Caching")]
        [TestMethod]
        public void VerifyCacheExpire()
        {
            string url = "http://localhost/Cache/Service1.svc/xml/12";
            Uri uri = new Uri(url);
            WebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string firstResponse = readStream.ReadLine();

            request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            response = (HttpWebResponse)request.GetResponse();
            receiveStream = response.GetResponseStream();
            readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string secondResponse = readStream.ReadLine();
            if (firstResponse.Equals(secondResponse))
            {
                Thread.Sleep(60000);

                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                response = (HttpWebResponse)request.GetResponse();
                receiveStream = response.GetResponseStream();
                readStream = new StreamReader(receiveStream, Encoding.UTF8);
                string thirdResponse = readStream.ReadLine();
                                
                if (firstResponse.Equals(thirdResponse))
                {
                    TestContext.WriteLine("Cache not expired for third request");
                    Assert.Fail();
                    
                }
                else
                {
                    TestContext.WriteLine("Cache expired during third request");
                }
            }

            else
            {
                TestContext.WriteLine("Cache expired during second request");
                Assert.Fail();
            }
            

        }

        [Description("Sample Unit TestCase where Webservice cache functionality is verified"),
        Owner("Ranjit Gupta"),
        TestCategory("Lookup Verification")]
        [TestMethod]
        public void Verify_DataSetRowcount()
        {

            WCFServiceRef.Service1Client obj = new WCFServiceRef.Service1Client();
            int expected = 21;
            DataSet ds = obj.Display();
            DataTable table = ds.Tables[0];
            int actual = table.Rows.Count;
            UnitTest help = new UnitTest();
            

            #if WEBSERVICES_FUNCTIONAL_TESTING
                help.Verify_RowCountDataSet(expected, actual);

            #endif
            #if WEBSERVICES_LOAD_TESTING
                                                                     //Any specific code if you want to run for Load testing alone
            #endif
        }

        [Description("Sample Unit TestCase where Webservice returns a complex object"),
        Owner("Ranjit Gupta"),
        TestCategory("DTO based Validations")]
        [TestMethod]
         public void VerifyComplexObjectDTO()
        {
            string connString = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
            string sql = "select * from Sample_App where Roll_Number=19";
            Student s = new Student();
            Student s1 = new Student();
            UnitTest help = new UnitTest();
            DataTable dt = help.GetDataTable(connString, sql);
            List<Student> ExpectedStudentDTOList = null;
            UnitTest helper = new UnitTest();
            ExpectedStudentDTOList = helper.DTO_PopulateDBResults<Student>(dt);
            Actions.DTO_Action complexObj = new Actions.DTO_Action();
            Object myObj = complexObj.ComplexObjectSample();

            #if WEBSERVICES_FUNCTIONAL_TESTING
                  object ActualStudentDTOList = helper.DTO_PopulateObject<Student>(myObj, s1);
                  bool result = helper.DTO_XmlComparison(ExpectedStudentDTOList, ActualStudentDTOList, typeof(List<Student>));
            #endif
            #if WEBSERVICES_LOAD_TESTING
                      //Any specific code if you want to run for Load testing alone
            #endif

            
        }
        
        [Description("Sample Unit TestCase where Webservice returns a dataset"),
        Owner("Ranjit Gupta"),
        TestCategory("DTO based Validations")]
        [TestMethod]
        public void VerifyDatasetDTO()
        {
            List<Student> list = new List<Student>();
            Student s = new Student();
            string connString = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
            string sql = "select * from Sample_App";
            UnitTest help = new UnitTest();
            DataTable dt = help.GetDataTable(connString, sql);
            List<Student> ExpectedStudentDTOList = null;
            List<Student> ActualStudentDTOList = null;
            UnitTest helper = new UnitTest();
            ExpectedStudentDTOList = helper.DTO_PopulateDBResults<Student>(dt);
            Actions.DTO_Action dsAction = new Actions.DTO_Action();
            ActualStudentDTOList = dsAction.GetDataTableSample();

            #if WEBSERVICES_FUNCTIONAL_TESTING
                        bool result = helper.DTO_XmlComparison(ExpectedStudentDTOList, ActualStudentDTOList, typeof(List<Student>));
            #endif
            #if WEBSERVICES_LOAD_TESTING
                       //Any specific code if you want to run for Load testing alone
            #endif

            
            
        }

        [Description("Sample Unit TestCase where Webservice returns a list"),
        Owner("Ranjit Gupta"),
        TestCategory("DTO based Validations")]
        [TestMethod]
        public void VerifyListDTO()
        {
            List<Student> list = new List<Student>();
            Student s = new Student();
            string connString = "Data Source=(local);Initial Catalog=Sample_DB;Integrated Security=True";
            string sql = "select Roll_Number from Sample_App";
            UnitTest helper = new UnitTest();
            DataTable dt = helper.GetDataTable(connString, sql);
            List<Student> ExpectedStudentDTOList = null;
            List<Student> ActualStudentDTOList = null;
            ExpectedStudentDTOList = helper.DTO_PopulateDBResults<Student>(dt);
            Actions.DTO_Action dsAction = new Actions.DTO_Action();
            ActualStudentDTOList = dsAction.GetRollNumbers();
            
            #if WEBSERVICES_FUNCTIONAL_TESTING
                        bool result = helper.DTO_XmlComparison(ExpectedStudentDTOList, ActualStudentDTOList, typeof(List<Student>));
            #endif
            #if WEBSERVICES_LOAD_TESTING
                                   //Any specific code if you want to run for Load testing alone
            #endif

        }
    }
}

    
